#include "mwworker.h"

#include <curl/curl.h>

#include <QFile>

static size_t DownloadCallback(void* pBuffer, size_t nSize, size_t nMemByte, void* pParam)
{
    QFile f;
    size_t ret;

    f.setFileName("test-curl");
    if (!f.open(QIODevice::Append))
        return 0;

    ret = f.write((const char*)pBuffer, nSize * nMemByte);

    return ret;
}

static int ProgressCallback(void *clientp, double dltotal, double dlnow, double ultotal, double ulnow)
{
    return 0;
}

mwWorker::mwWorker()
{
    isrun = true;
}

mwWorker::~mwWorker()
{
    isrun = false;
}

void mwWorker::run()
{
    //初始化curl，这个是必须的
    CURL* curl;
    QFile f;
    curl_off_t pos = 1024*100;

    f.setFileName("test-curl");
    f.remove();

    curl = curl_easy_init();
    curl_easy_setopt(curl, CURLOPT_URL, "http://www.enkj.lvruan.com/uploadfile/2018/Dark_hjkjkl.zip");

    //设置接收数据的回调
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, DownloadCallback);
    curl_easy_setopt(curl, CURLOPT_RESUME_FROM_LARGE, pos);

    // 设置重定向的最大次数
    curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 5);
    // 设置301、302跳转跟随location
    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
    curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
    //设置进度回调函数
    curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, ProgressCallback);

    //开始执行请求
    CURLcode retcCode = curl_easy_perform(curl);
    //查看是否有出错信息
    const char* pError = curl_easy_strerror(retcCode);

    qDebug(pError);

    //清理curl，和前面的初始化匹配
    curl_easy_cleanup(curl);
}
